/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By www.gzchengguo.cn
* 注意：
* 本软件为www.gzchengguo.cn开发研制，未经购买不得商用
* 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
* 一经发现盗用、分享等行为，将追究法律责任，后果自负
*/
package link.chengguo.orangemall.modules.user.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import link.chengguo.orangemall.api.ApiCode;
import link.chengguo.orangemall.api.UnAuthenticatedException;
import link.chengguo.orangemall.common.service.impl.BaseServiceImpl;
import link.chengguo.orangemall.common.utils.QueryHelpPlus;
import link.chengguo.orangemall.constant.SystemConfigConstants;
import link.chengguo.orangemall.dozer.service.IGenerator;

import link.chengguo.orangemall.enums.BillDetailEnum;
import link.chengguo.orangemall.enums.Brokerage;
import link.chengguo.orangemall.enums.ShopCommonEnum;
import link.chengguo.orangemall.modules.activity.service.OrangeStoreCouponUserService;
import link.chengguo.orangemall.modules.cart.vo.OrangeStoreCartQueryVo;
import link.chengguo.orangemall.modules.order.domain.OrangeStoreOrderCartInfo;
import link.chengguo.orangemall.modules.order.service.OrangeStoreOrderCartInfoService;
import link.chengguo.orangemall.modules.order.service.OrangeStoreOrderService;
import link.chengguo.orangemall.modules.order.service.mapper.StoreOrderMapper;
import link.chengguo.orangemall.modules.order.vo.OrangeStoreOrderQueryVo;
import link.chengguo.orangemall.modules.product.domain.OrangeStoreProductAttrValue;
import link.chengguo.orangemall.modules.product.vo.OrangeStoreProductQueryVo;
import link.chengguo.orangemall.modules.shop.domain.OrangeSystemUserLevel;
import link.chengguo.orangemall.modules.shop.service.OrangeSystemConfigService;
import link.chengguo.orangemall.modules.shop.service.OrangeSystemStoreStaffService;
import link.chengguo.orangemall.modules.user.domain.OrangeUser;
import link.chengguo.orangemall.modules.user.domain.OrangeUserLevel;
import link.chengguo.orangemall.modules.user.service.OrangeSystemUserLevelService;
import link.chengguo.orangemall.modules.user.service.OrangeUserBillService;
import link.chengguo.orangemall.modules.user.service.OrangeUserLevelService;
import link.chengguo.orangemall.modules.user.service.OrangeUserService;
import link.chengguo.orangemall.modules.user.service.dto.PromUserDto;
import link.chengguo.orangemall.modules.user.service.dto.UserMoneyDto;
import link.chengguo.orangemall.modules.user.service.dto.OrangeUserDto;
import link.chengguo.orangemall.modules.user.service.dto.OrangeUserQueryCriteria;
import link.chengguo.orangemall.modules.user.service.mapper.UserBillMapper;
import link.chengguo.orangemall.modules.user.service.mapper.UserMapper;
import link.chengguo.orangemall.modules.user.vo.OrangeUserQueryVo;
import link.chengguo.orangemall.utils.FileUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author chengguo
* @date 2020-05-12
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class OrangeUserServiceImpl extends BaseServiceImpl<UserMapper, OrangeUser> implements OrangeUserService {

    @Autowired
    private IGenerator generator;

    @Autowired
    private UserMapper orangeUserMapper;
    @Autowired
    private StoreOrderMapper storeOrderMapper;
    @Autowired
    private UserBillMapper userBillMapper;


    @Autowired
    private OrangeSystemUserLevelService systemUserLevelService;
    @Autowired
    private OrangeUserLevelService userLevelService;
    @Autowired
    private OrangeStoreOrderService orderService;
    @Autowired
    private OrangeSystemConfigService systemConfigService;
    @Autowired
    private OrangeUserBillService billService;
    @Autowired
    private OrangeStoreCouponUserService storeCouponUserService;
    @Autowired
    private OrangeSystemStoreStaffService systemStoreStaffService;
    @Autowired
    private OrangeStoreOrderCartInfoService storeOrderCartInfoService;


    /**
     * 返回用户累计充值金额与消费金额
     * @param uid uid
     * @return Double[]
     */
    @Override
    public Double[] getUserMoney(Long uid){
        double sumPrice = storeOrderMapper.sumPrice(uid);
        double sumRechargePrice = userBillMapper.sumRechargePrice(uid);
        return new Double[]{sumPrice,sumRechargePrice};
    }


    /**
     * 增加购买次数
     * @param uid uid
     */
    @Override
    public void incPayCount(Long uid) {
        orangeUserMapper.incPayCount(uid);
    }

    /**
     * 减去用户余额
     * @param uid uid
     * @param payPrice 金额
     */
    @Override
    public void decPrice(Long uid, BigDecimal payPrice) {
        orangeUserMapper.decPrice(payPrice,uid);
    }

    /**
     * 减去用户积分
     * @param uid 用户id
     * @param integral 积分
     */
    @Override
    public void decIntegral(Long uid, double integral) {
        orangeUserMapper.decIntegral(integral,uid);
    }


    /**
     * 获取我的分销下人员列表
     * @param uid uid
     * @param page page
     * @param limit limit
     * @param grade ShopCommonEnum.GRADE_0
     * @param keyword 关键字搜索
     * @param sort 排序
     * @return list
     */
    @Override
    public List<PromUserDto> getUserSpreadGrade(Long uid, int page, int limit, Integer grade,
                                                String keyword, String sort) {
        List<OrangeUser> userList = orangeUserMapper.selectList(Wrappers.<OrangeUser>lambdaQuery()
                .eq(OrangeUser::getSpreadUid, uid));
        List<Long> userIds = userList.stream()
                .map(OrangeUser::getUid)
                .collect(Collectors.toList());

        List<PromUserDto> list = new ArrayList<>();
        if (userIds.isEmpty()) {
            return list;
        }

        if (StrUtil.isBlank(sort)) {
            sort = "u.uid desc";
        }

        Page<OrangeUser> pageModel = new Page<>(page, limit);
        if (ShopCommonEnum.GRADE_0.getValue().equals(grade)) {//-级
            list = orangeUserMapper.getUserSpreadCountList(pageModel, userIds,
                    keyword, sort);
        } else {//二级
            List<OrangeUser> userListT = orangeUserMapper.selectList(Wrappers.<OrangeUser>lambdaQuery()
                    .in(OrangeUser::getSpreadUid, userIds));
            List<Long> userIdsT = userListT.stream()
                    .map(OrangeUser::getUid)
                    .collect(Collectors.toList());
            if (userIdsT.isEmpty()) {
                return list;
            }
            list = orangeUserMapper.getUserSpreadCountList(pageModel, userIdsT,
                    keyword, sort);

        }
        return list;
    }

    /**
     * 统计分销人员
     * @param uid uid
     * @return map
     */
    @Override
    public Map<String,Integer> getSpreadCount(Long uid) {
        int countOne = orangeUserMapper.selectCount(Wrappers.<OrangeUser>lambdaQuery()
                .eq(OrangeUser::getSpreadUid,uid));

        int countTwo = 0;
        List<OrangeUser> userList = orangeUserMapper.selectList((Wrappers.<OrangeUser>lambdaQuery()
                .eq(OrangeUser::getSpreadUid,uid)));
        List<Long> userIds = userList.stream().map(OrangeUser::getUid)
                .collect(Collectors.toList());
        if(!userIds.isEmpty()){
            countTwo = orangeUserMapper.selectCount(Wrappers.<OrangeUser>lambdaQuery()
                    .in(OrangeUser::getSpreadUid,userIds));
        }

        Map<String,Integer> map = new LinkedHashMap<>(2);
        map.put("first",countOne); //一级
        map.put("second",countTwo);//二级

        return map;
    }

    /**
     * 一级返佣
     * @param order 订单
     */
    @Override
    public void backOrderBrokerage(OrangeStoreOrderQueryVo order) {
        //如果分销没开启直接返回
        String open = systemConfigService.getData(SystemConfigConstants.STORE_BROKERAGE_OPEN);
        if(StrUtil.isBlank(open) || ShopCommonEnum.ENABLE_2.getValue().toString().equals(open)) {
            return;
        }


        //获取购买商品的用户
        OrangeUser userInfo =  this.getById(order.getUid());
        System.out.println("userInfo:"+userInfo);
        //当前用户不存在 没有上级  直接返回
        if(ObjectUtil.isNull(userInfo) || userInfo.getSpreadUid() == 0) {
            return;
        }


        OrangeUser preUser = this.getById(userInfo.getSpreadUid());

        //一级返佣金额
        BigDecimal brokeragePrice = this.computeProductBrokerage(order, Brokerage.LEVEL_1);

        //返佣金额小于等于0 直接返回不返佣金

        if(brokeragePrice.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        //计算上级推广员返佣之后的金额
        double balance = NumberUtil.add(preUser.getBrokeragePrice(),brokeragePrice).doubleValue();
        String mark = userInfo.getNickname()+"成功消费"+order.getPayPrice()+"元,奖励推广佣金"+
                brokeragePrice;
        //增加流水
        billService.income(userInfo.getSpreadUid(),"获得推广佣金", BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_2.getValue(),brokeragePrice.doubleValue(),balance, mark,order.getId().toString());

        //添加用户余额
        orangeUserMapper.incBrokeragePrice(brokeragePrice, userInfo.getSpreadUid());

        //一级返佣成功 跳转二级返佣
        this.backOrderBrokerageTwo(order);

    }




    /**
     * 更新用户余额
     * @param uid y用户id
     * @param price 金额
     */
    @Override
    public void incMoney(Long uid, BigDecimal price) {
        orangeUserMapper.incMoney(uid,price);
    }

    /**
     * 增加积分
     * @param uid uid
     * @param integral 积分
     */
    @Override
    public void incIntegral(Long uid, double integral) {
        orangeUserMapper.incIntegral(integral,uid);
    }


    /**
     * 获取用户信息
     * @param uid uid
     * @return OrangeUserQueryVo
     */
    @Override
    public OrangeUserQueryVo getOrangeUserById(Long uid) {
        return generator.convert(this.getById(uid), OrangeUserQueryVo.class);
    }


    /**
     * 转换用户信息
     * @param orangeUser user
     * @return OrangeUserQueryVo
     */
    @Override
    public OrangeUserQueryVo handleUser(OrangeUser orangeUser) {
        return generator.convert(orangeUser, OrangeUserQueryVo.class);
    }

    /**
     * 获取用户个人详细信息
     * @param orangeUser orangeUser
     * @return OrangeUserQueryVo
     */
    @Override
    public OrangeUserQueryVo getNewOrangeUserById(OrangeUser orangeUser) {
        OrangeUserQueryVo userQueryVo = generator.convert(orangeUser, OrangeUserQueryVo.class);
        OrangeUserLevel userLevel = userLevelService.getUserLevel(orangeUser.getUid(), null);
        if(userLevel != null && userLevel.getStatus().equals(1)){
            OrangeSystemUserLevel systemUserLevel = systemUserLevelService.getById(userLevel.getLevelId());
            if(systemUserLevel != null){
                userQueryVo.setVip(true);
                userQueryVo.setVipId(userLevel.getId());
                userQueryVo.setVipIcon(systemUserLevel.getIcon());
                userQueryVo.setVipName(systemUserLevel.getName());
            }
        }
        if(userQueryVo == null){
            throw new UnAuthenticatedException(ApiCode.UNAUTHORIZED);
        }
        userQueryVo.setOrderStatusNum(orderService.orderData(orangeUser.getUid()));
        userQueryVo.setCouponCount(storeCouponUserService.getUserValidCouponCount(orangeUser.getUid()));
        //判断分销类型,指定分销废弃掉，只有一种分销方式
        /**
            String statu = systemConfigService.getData(SystemConfigConstants.STORE_BROKERAGE_STATU);
            if(StrUtil.isNotEmpty(statu)){
                userQueryVo.setStatu(Integer.valueOf(statu));
            }else{
                userQueryVo.setStatu(0);
            }
         **/

        //获取核销权限
        userQueryVo.setCheckStatus(systemStoreStaffService.checkStatus(orangeUser.getUid(),null));

        this.setUserSpreadCount(orangeUser);
        return userQueryVo;
    }



    /**
     * 返回会员价
     * @param productAttrValue 规格参数
     * @param uid 用户id
     * @return vip 价格
     */
    @Override
    public double setLevelPrice(OrangeStoreProductAttrValue productAttrValue, long uid) {
        QueryWrapper<OrangeUserLevel> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(OrangeUserLevel::getStatus, ShopCommonEnum.IS_STATUS_1.getValue())
                .eq(OrangeUserLevel::getUid,uid)
                .orderByDesc(OrangeUserLevel::getGrade)
                .last("limit 1");
        OrangeUserLevel userLevel = userLevelService.getOne(wrapper);
        OrangeSystemUserLevel systemUserLevel = new OrangeSystemUserLevel();
        if(ObjectUtil.isNotNull(userLevel)) {
            systemUserLevel=  systemUserLevelService.getById(userLevel.getLevelId());
        }
        int discount = 100;
        if(ObjectUtil.isNotNull(userLevel)) {
            discount = systemUserLevel.getDiscount().intValue();
        }

        try{
            //重新设置vip价格
            String vipPriceJson = productAttrValue.getVipPrice();
            if(StrUtil.isNotBlank(vipPriceJson)){
                List<Map<String,Object>> list = JSON.parseObject(vipPriceJson, List.class);
                    for (Map<String, Object> map : list) {
                        int id = (int) map.get("id");
                        if(id == userLevel.getLevelId()){
                            if(StrUtil.isNotBlank(map.get("price").toString())){
                                return Double.parseDouble(map.get("price").toString());
                            }else {
                                break;
                            }
                        }
                    }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return NumberUtil.mul(NumberUtil.div(discount,100),productAttrValue.getPrice().doubleValue());
    }


    /**
     * 设置推广关系
     * @param spread 上级人
     * @param uid 本人
     */
    @Override
    public void setSpread(String spread, long uid) {
        if(StrUtil.isBlank(spread) || !NumberUtil.isNumber(spread)) {
            return;
        }

        //如果分销没开启直接返回
        String open = systemConfigService.getData(SystemConfigConstants.STORE_BROKERAGE_OPEN);
        if(StrUtil.isBlank(open) || ShopCommonEnum.ENABLE_2.getValue().toString().equals(open)) {
            return;
        }
        //当前用户信息
        OrangeUser userInfo = this.getById(uid);
        if(ObjectUtil.isNull(userInfo)) {
            return;
        }

        //当前用户有上级直接返回
        if(userInfo.getSpreadUid() != null && userInfo.getSpreadUid() > 0) {
            return;
        }
        //没有推广编号直接返回
        long spreadInt = Long.valueOf(spread);
        if(spreadInt == 0) {
            return;
        }
        if(spreadInt == uid) {
            return;
        }

        //不能互相成为上下级
        OrangeUser userInfoT = this.getById(spreadInt);
        if(ObjectUtil.isNull(userInfoT)) {
            return;
        }

        if(userInfoT.getSpreadUid() == uid) {
            return;
        }

        OrangeUser orangeUser = OrangeUser.builder()
                .spreadUid(spreadInt)
                .spreadTime(new Date())
                .uid(uid)
                .build();

        orangeUserMapper.updateById(orangeUser);

    }


    /**
     * 二级返佣
     * @param order 订单
     */
    private void backOrderBrokerageTwo(OrangeStoreOrderQueryVo order) {

        OrangeUser userInfo =  this.getById(order.getUid());

        //获取上推广人
        OrangeUser userInfoTwo = this.getById(userInfo.getSpreadUid());

        //上推广人不存在 或者 上推广人没有上级    直接返回
        if(ObjectUtil.isNull(userInfoTwo) || userInfoTwo.getSpreadUid() == 0) {
            return;
        }


        //指定分销 判断 上上级是否时推广员  如果不是推广员直接返回
        OrangeUser preUser = this.getById(userInfoTwo.getSpreadUid());


        //二级返佣金额
        BigDecimal brokeragePrice = this.computeProductBrokerage(order,Brokerage.LEVEL_2);

        //返佣金额小于等于0 直接返回不返佣金
        if(brokeragePrice.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }

        //获取上上级推广员信息
        double balance = NumberUtil.add(preUser.getBrokeragePrice(),brokeragePrice).doubleValue();
        String mark = "二级推广人"+userInfo.getNickname()+"成功消费"+order.getPayPrice()+"元,奖励推广佣金"+
                brokeragePrice;

        //增加流水
        billService.income(userInfoTwo.getSpreadUid(),"获得推广佣金",BillDetailEnum.CATEGORY_1.getValue(),
                BillDetailEnum.TYPE_2.getValue(),brokeragePrice.doubleValue(),balance, mark,order.getId().toString());
        //添加用户余额
        orangeUserMapper.incBrokeragePrice(brokeragePrice,
                userInfoTwo.getSpreadUid());
    }


    /**
     * 计算获取返佣金额
     * @param order 订单信息
     * @param level 分销级别
     * @return double
     */
    private BigDecimal computeProductBrokerage(OrangeStoreOrderQueryVo order , Brokerage level){
        List<OrangeStoreOrderCartInfo> storeOrderCartInfoList = storeOrderCartInfoService
                .list(Wrappers.<OrangeStoreOrderCartInfo>lambdaQuery()
                        .in(OrangeStoreOrderCartInfo::getCartId, Arrays.asList(order.getCartId().split(","))));
        BigDecimal oneBrokerage = BigDecimal.ZERO;//一级返佣金额
        BigDecimal twoBrokerage = BigDecimal.ZERO;//二级返佣金额

        List<String> cartInfos = storeOrderCartInfoList.stream()
                .map(OrangeStoreOrderCartInfo::getCartInfo)
                .collect(Collectors.toList());

        for (String cartInfo : cartInfos){
            OrangeStoreCartQueryVo cart = JSON.parseObject(cartInfo, OrangeStoreCartQueryVo.class);

            OrangeStoreProductQueryVo storeProductVO = cart.getProductInfo();
            //产品是否单独分销
            if(ShopCommonEnum.IS_SUB_1.getValue().equals(storeProductVO.getIsSub())){
                oneBrokerage = NumberUtil.round(NumberUtil.add(oneBrokerage,
                        NumberUtil.mul(cart.getCartNum(),storeProductVO.getAttrInfo().getBrokerage()))
                        ,2);

                twoBrokerage = NumberUtil.round(NumberUtil.add(twoBrokerage,
                        NumberUtil.mul(cart.getCartNum(),storeProductVO.getAttrInfo().getBrokerageTwo()))
                        ,2);
            }

        }

        //获取后台一级返佣比例
        String storeBrokerageRatioStr = systemConfigService.getData(SystemConfigConstants.STORE_BROKERAGE_RATIO);
        String storeBrokerageTwoStr = systemConfigService.getData(SystemConfigConstants.STORE_BROKERAGE_TWO);


        //一级返佣比例未设置直接返回
        if(StrUtil.isBlank(storeBrokerageRatioStr)
                || !NumberUtil.isNumber(storeBrokerageRatioStr)){
            return oneBrokerage;
        }
        //二级返佣比例未设置直接返回
        if(StrUtil.isBlank(storeBrokerageTwoStr)
                || !NumberUtil.isNumber(storeBrokerageTwoStr)){
            return twoBrokerage;
        }


        switch (level){
            case LEVEL_1:
                //根据订单获取一级返佣比例
                BigDecimal storeBrokerageRatio = NumberUtil.round(NumberUtil.div(storeBrokerageRatioStr,"100"),2);
                BigDecimal brokeragePrice = NumberUtil
                        .round(NumberUtil.mul(order.getTotalPrice(),storeBrokerageRatio),2);
                //固定返佣 + 比例返佣 = 总返佣金额
                return NumberUtil.add(oneBrokerage,brokeragePrice);
            case LEVEL_2:
                //根据订单获取一级返佣比例
                BigDecimal storeBrokerageTwo = NumberUtil.round(NumberUtil.div(storeBrokerageTwoStr,"100"),2);
                BigDecimal storeBrokerageTwoPrice = NumberUtil
                        .round(NumberUtil.mul(order.getTotalPrice(),storeBrokerageTwo),2);
                //固定返佣 + 比例返佣 = 总返佣金额
                return NumberUtil.add(twoBrokerage,storeBrokerageTwoPrice);
        }


        return BigDecimal.ZERO;

    }



    /**
     * 更新下级人数
     * @param orangeUser user
     */
    private void setUserSpreadCount(OrangeUser orangeUser) {
        int count = orangeUserMapper.selectCount(Wrappers.<OrangeUser>lambdaQuery()
                .eq(OrangeUser::getSpreadUid, orangeUser.getUid()));
        orangeUser.setSpreadCount(count);
        orangeUserMapper.updateById(orangeUser);
    }


    //===========后面管理后台部分=====================//


    /**
     * 查看下级
     * @param uid uid
     * @param grade 等级
     * @return list
     */
    @Override
    public List<PromUserDto> querySpread(Long uid, Integer grade) {
        return this.getUserSpreadGrade(uid,1, 999,grade,"","");
    }


    @Override
    public Map<String, Object> queryAll(OrangeUserQueryCriteria criteria, Pageable pageable) {
        getPage(pageable);
        PageInfo<OrangeUser> page = new PageInfo<>(queryAll(criteria));
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), OrangeUserDto.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    @Override
    //@Cacheable
    public List<OrangeUser> queryAll(OrangeUserQueryCriteria criteria){
        return baseMapper.selectList(QueryHelpPlus.getPredicate(OrangeUser.class, criteria));
    }


    @Override
    public void download(List<OrangeUserDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (OrangeUserDto orangeUser : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户账户(跟accout一样)", orangeUser.getUsername());
            map.put("用户密码（跟pwd）", orangeUser.getPassword());
            map.put("真实姓名", orangeUser.getRealName());
            map.put("生日", orangeUser.getBirthday());
            map.put("身份证号码", orangeUser.getCardId());
            map.put("用户备注", orangeUser.getMark());
            map.put("合伙人id", orangeUser.getPartnerId());
            map.put("用户分组id", orangeUser.getGroupId());
            map.put("用户昵称", orangeUser.getNickname());
            map.put("用户头像", orangeUser.getAvatar());
            map.put("手机号码", orangeUser.getPhone());
            map.put("添加时间", orangeUser.getCreateTime());
            map.put("添加ip", orangeUser.getAddIp());
            map.put("用户余额", orangeUser.getNowMoney());
            map.put("佣金金额", orangeUser.getBrokeragePrice());
            map.put("用户剩余积分", orangeUser.getIntegral());
            map.put("连续签到天数", orangeUser.getSignNum());
            map.put("1为正常，0为禁止", orangeUser.getStatus());
            map.put("等级", orangeUser.getLevel());
            map.put("推广元id", orangeUser.getSpreadUid());
            map.put("推广员关联时间", orangeUser.getSpreadTime());
            map.put("用户类型", orangeUser.getUserType());
            map.put("是否为推广员", orangeUser.getIsPromoter());
            map.put("用户购买次数", orangeUser.getPayCount());
            map.put("下级人数", orangeUser.getSpreadCount());
            map.put("详细地址", orangeUser.getAddres());
            map.put("管理员编号 ", orangeUser.getAdminid());
            map.put("用户登陆类型，h5,wechat,routine", orangeUser.getLoginType());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 更新用户状态
     * @param uid uid
     * @param status ShopCommonEnum
     */
    @Override
    public void onStatus(Long uid, Integer status) {
        if(ShopCommonEnum.IS_STATUS_1.getValue().equals(status)){
            status = ShopCommonEnum.IS_STATUS_0.getValue();
        }else{
            status = ShopCommonEnum.IS_STATUS_1.getValue();
        }
        orangeUserMapper.updateOnstatus(status,uid);
    }
    /**
     * 更新用户状态
     * @param uid uid
     * @param authType ShopCommonEnum
     */
    @Override
    public void onAuthType(Long uid, Integer authType) {
        if(ShopCommonEnum.AUTH_NO.getValue().equals(authType)){
            authType = ShopCommonEnum.AUTH_NO.getValue();
        }else if(ShopCommonEnum.AUTH_OK.getValue().equals(authType)){
            authType = ShopCommonEnum.AUTH_OK.getValue();
        }else if(ShopCommonEnum.AUTH_FAIL.getValue().equals(authType)){
            authType = ShopCommonEnum.AUTH_FAIL.getValue();
        }
        orangeUserMapper.updateonAuthType(authType,uid);
    }

    /**
     * 修改余额
     * @param param UserMoneyDto
     */
    @Override
    public void updateMoney(UserMoneyDto param) {
        OrangeUser orangeUser = this.getById(param.getUid());
        double newMoney = 0d;
        String mark = "";
        if(param.getPtype() == 1){
            mark = "系统增加了"+param.getMoney()+"余额";
            newMoney = NumberUtil.add(orangeUser.getNowMoney(),param.getMoney()).doubleValue();
            billService.income(orangeUser.getUid(),"系统增加余额", BillDetailEnum.CATEGORY_1.getValue(),
                    BillDetailEnum.TYPE_6.getValue(),param.getMoney(),newMoney, mark,"");
        }else{
            mark = "系统扣除了"+param.getMoney()+"余额";
            newMoney = NumberUtil.sub(orangeUser.getNowMoney(),param.getMoney()).doubleValue();
            if(newMoney < 0) {
                newMoney = 0d;
            }
            billService.expend(orangeUser.getUid(), "系统减少余额",
                    BillDetailEnum.CATEGORY_1.getValue(),
                    BillDetailEnum.TYPE_7.getValue(),
                    param.getMoney(), newMoney, mark);
        }
//        OrangeUser user = new OrangeUser();
//        user.setUid(orangeUser.getUid());
        orangeUser.setNowMoney(BigDecimal.valueOf(newMoney));
        saveOrUpdate(orangeUser);
    }

    /**
     * 增加佣金
     * @param price 金额
     * @param uid 用户id
     */
    @Override
    public void incBrokeragePrice(BigDecimal price, Long uid) {
        orangeUserMapper.incBrokeragePrice(price,uid);
    }
}
